//
//  BLEViewController.m
//  BLESDK
//
//  Created by liyang on 05/17/2018.
//  Copyright (c) 2018 liyang. All rights reserved.
//

/*
 http://www.cocoachina.com/ios/20180516/23394.html
 使用Cocoapods创建私有podspec
 http://blog.wtlucky.com/blog/2015/02/26/create-private-podspec/
 */

#import "BLEViewController.h"

#import <BLESDK/BLESDK.h>
#import <UITableView+LYAdd.h>

#import <UIFont+LYAdd.h>
#import <LYProgressHUD.h>
@interface BLEViewController ()
<UITableViewDelegate,
UITableViewDataSource>

/// 蓝牙中心
@property (nonatomic, strong) BLECenter *center;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *deviceNameTF;

///
@property (nonatomic, strong) NSMutableArray<BLEDevice *> *devices;

@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@end

@implementation BLEViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bleCenterStateDidUpdate:) name:BLECenterStateDidChangeNotification object:nil];
//    dispatch_queue_t queue = dispatch_queue_create("com.best", DISPATCH_QUEUE_CONCURRENT);
    
    [self.tableView registerCellWithClass:[UITableViewCell class]];
    [self center];
    
//    [self.center connectAutomaticallyWithTimeout:10 options:nil completion:^(NSTimeInterval use, NSError *error) {
//        BLELog(@"自动连接设备，用时%lf，错误：%@", use, error);
//    }];
}
- (void)bleCenterStateDidUpdate:(NSNotification *)notify
{
    NSLog(@"%@",notify.userInfo);
}


- (IBAction)testAction:(id)sender
{
    [self.center sentRequest:nil
                     success:^(__kindof BLETask *task, BLERequest *request) {
                         
                     }
                     failure:^(__kindof BLETask *task, NSError *error) {
                         
                     }];
}
- (IBAction)disconnectAction:(id)sender
{

    [self.center cancelConnectionWithTimeout:10 completion:^(NSTimeInterval use, NSError *error) {
        NSLog(@"断开设备连接，用时%lf，错误：%@", use, error);
    }];
}
- (IBAction)conntectAction:(id)sender
{
    [LYProgressHUD showLoading];
    NSString *name = self.deviceNameTF.text;
    if (!name.length)
    {
        [self.center connectAutomaticallyWithTimeout:10 options:nil completion:^(NSTimeInterval use, NSError *error) {
            [LYProgressHUD dismiss];
            NSLog(@"连接设备 %@，用时%lf，错误：%@", name, use, error);
        }];
    }
    else
    {
        [self.center connectToDeviceNamed:name timeout:10 options:nil completion:^(NSTimeInterval use, NSError *error) {
            [LYProgressHUD dismiss];
            NSLog(@"连接设备 %@，用时%lf，错误：%@", name, use, error);
        }];
    }
}

- (IBAction)searchAction:(id)sender
{
    
    
    
    [self.devices removeAllObjects];
    [LYProgressHUD showLoading];
    [self.center searchDevicesWithTimeout:10 filterBlock:^BOOL(NSString *name, NSNumber *rssi) {
        return [name hasPrefix:@"ZeTime"];
//        return YES;
    } progress:^(BLEDevice *device, NSTimeInterval use, BOOL *stop) {
        NSLog(@"discover -- name:%@ use:%lf RSSI:%@", device.name, use, device.RSSI);
        [self.devices addObject:device];
        [self.tableView reloadData];
        
    } completion:^(NSTimeInterval use, NSError *error) {
        [LYProgressHUD dismiss];
        NSLog(@"search completion %@ %lf", error, use);
    }];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.devices.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCell:[UITableViewCell class]];
    BLEDevice *device = self.devices[indexPath.row];
    cell.textLabel.text = device.name;
    cell.detailTextLabel.text = device.RSSI.stringValue;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BLEDevice *device = self.devices[indexPath.row];
    [self.center connectToDevice:device
                         timeout:10
                         options:nil
                      completion:^(NSTimeInterval use, NSError *error) {
                          NSLog(@"连接设备，%lf, %@", use, error);
    }];
}

- (NSMutableArray<BLEDevice *> *)devices {
    if (_devices) return _devices;
    _devices = [NSMutableArray array];
    return _devices;
}

- (BLECenter *)center {
    if (_center) return _center;
//    BLECenterConfig *config = [BLECenterConfig defaultConfig];
//    config.connectAutomatically = NO;
//    _center = [[BLECenter alloc]initWithConfig:config];
    _center = [BLECenter center];
    return _center;
}

@end
